
import axios from "axios";
import { Message } from "element-ui";

import store from "@/store";
import router from "@/router";

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000,
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    if (store.getters.token) {
      config.headers.Authorization = "Bearer " + store.getters.token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const { success, data, msg } = response.data;
    if (success) {
      return data;
    } else {
      Message.error(msg);
      return Promise.reject(msg);
    }
  },
  (error) => {
    // console.log(error)
    // console.log(error.response)
    if (
      error.response &&
      error.response.data &&
      !error.response.data.msg == "token错误，请重新获取！"
    ) {
      store.dispatch("user/quitAction");
      router.push("/login");
      Message.error("token过期, 请重新登录");
    } else {
      Message.error(error.msg);
    }
    return Promise.reject(error);
  }
);

export default service;

